import Vue from 'vue'
import _ from 'lodash'
import VueRouter from 'vue-router'
import { commonRouter, diffRouter } from './data'
import store from '@/store'
import ElementUI from 'element-ui'
import { mobileExchange } from '@/api'

Vue.use(VueRouter)

const routes = [...commonRouter]

const router = new VueRouter({
	// mode: 'history',
	base: process.env.BASE_URL,
	routes
})

var urlParams = new URLSearchParams(location.search)
// 导航之前拦截器
router.beforeEach(async (to, from, next) => {
	console.log('beforeEach to:', to)
	if (to.meta.anonymous) {
		next()
		return
	}
	if (!store.getters.token) {
		var authCode = urlParams.get('authCode')
		if (authCode) {
			try {
				const { data } = await mobileExchange({ authCode })
				ElementUI.Message({
					message: '验证码已发送至' + data,
					type: 'success'
				})
				next('/login')
				return
			} catch (e) {
				ElementUI.Message({
					message: '校验码无效，请检查链接是否完整',
					type: 'error'
				})
			}
		} else {
			ElementUI.Message({
				message: '校验码无效，请检查链接是否完整',
				type: 'error'
			})
		}
	} else {
		if (!store.getters.userInfo) {
			await store.dispatch('getUserInfo')
		}
		if (!store.getters.signInfo) {
			await store.dispatch('getSignatures')
		}
		next()
	}
})
export default router
